<template>
  <n-select
    ref="selectInstRef"
    :value="state.author"
    filterable
    placeholder="请输入人员名称"
    :options="authorOptions"
    :loading="state.loading"
    :render-label="renderLabel"
    :render-tag="renderSingleSelectTag"
    label-field="username"
    value-field="id"
    clearable
    :clear-filter-after-select="false"
    @search="handleSearch"
    @update:show="showChange"
    @update:value="handChange"
  >
    <template #header>
      <n-button @click="handOpen">列表选择</n-button>
    </template>
  </n-select>
  <teleport to="body">
    <choose-user ref="userRef" @change="userChange" />
  </teleport>
</template>
<script setup lang="ts">
import { NSelect, NButton, NAvatar, NText } from 'naive-ui'
import type { SelectRenderLabel, SelectRenderTag, SelectInst } from 'naive-ui'
import { h, reactive, ref, watch } from 'vue'
import photoUserApi from '@/service/api/photo/user'
import ChooseUser from '@/components/yang/yselectuser/ChooseUser.vue'
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  }
})
interface userItem {
  id: number
  avatar: string
  username: string
  institution_name: string
}
interface stateItem {
  loading: boolean
  author: number | string
}
const checkUser = ref<userItem>({
  id: 0,
  avatar: '',
  username: '',
  institution_name: ''
})
const userRef = ref()
const selectInstRef = ref<SelectInst | null>(null)
const handOpen = () => {
  userRef.value.open()
  selectInstRef.value?.blur()
}
const userChange = (row: userItem) => {
  checkUser.value = row
  const status = authorOptions.value.some(item => item.id === row.id)
  if (!status) {
    authorOptions.value.push(row)
  }
  handChange(row.id)
}
const showChange = (show: boolean) => {
  if (show && authorOptions.value.length === 0) {
    handleSearch('')
  }
}
const emit = defineEmits(['update:modelValue', 'change'])
const handChange = (e: number) => {
  const info = authorOptions.value.find((item: any) => item.id === e)
  emit('update:modelValue', e)
  emit('change', info)
  state.author = e
}
const state: stateItem = reactive({
  loading: false,
  author: ''
})
const authorOptions = ref<userItem[]>([])
const handleSearch = (username: string) => {
  state.loading = true
  photoUserApi
    .list({
      pageNo: 1,
      pageSize: 10,
      username
    })
    .then(({ data }) => {
      state.loading = false
      authorOptions.value = data.data
    })
}
const renderSingleSelectTag: SelectRenderTag = ({ option }) => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center'
      }
    },
    [
      h(NAvatar, {
        src: option.avatar,
        round: true,
        size: 24,
        style: {
          marginRight: '12px'
        }
      }),
      option.username as string
    ]
  )
}
const renderLabel: SelectRenderLabel = option => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center'
      }
    },
    [
      h(NAvatar, {
        src: option.avatar,
        round: true,
        size: 'small'
      }),
      h(
        'div',
        {
          style: {
            marginLeft: '12px',
            padding: '4px 0',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between'
          }
        },
        [
          h('div', null, [option.username as string]),
          h(
            NText,
            { depth: 3, tag: 'div' },
            {
              default: () => `[${option.institution_name}]`
            }
          )
        ]
      )
    ]
  )
}

const getOptions = (id: any) => {
  photoUserApi
    .list({
      pageNo: 1,
      pageSize: 10,
      id
    })
    .then(({ data }) => {
      authorOptions.value = data.data
    })
}
watch(
  () => props.modelValue,
  newVal => {
    state.author = newVal
    if (newVal && !authorOptions.value.some(item => item.id === newVal)) {
      getOptions(newVal)
    }
  },
  {
    immediate: true
  }
)
defineExpose({
  getOptions
})
</script>

<style scoped lang="scss"></style>
